package com.epam.iunna.bookshop.controller.actions;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.epam.iunna.bookshop.controller.application.Constants;
import com.epam.iunna.bookshop.controller.filters.AuthFilter;
import com.epam.iunna.bookshop.controller.utils.dispatch.ActionInt;
import com.epam.iunna.bookshop.model.User;
import com.epam.iunna.bookshop.model.UserDao;
import com.epam.iunna.bookshop.model.service.BasketBean;

public class AddMoney implements ActionInt{

    @Override
    public String perform(HttpServletRequest request,
            HttpServletResponse response) {
        try{
         
            String money = request.getParameter("money");
            
            Map<String,String> errorMap = new HashMap<String,String>();
            
            BigDecimal moneyBigDec = null;
            try{
                moneyBigDec = new BigDecimal(money);
            }catch(Exception e){
                errorMap.put("money", " not a number");
            }
            if( money.isEmpty() ){
                errorMap.put("moneyObj", " * required");
            }
            if( !errorMap.isEmpty() ){
                request.setAttribute("errorMap", errorMap);
                return "./addMoney.jsp";
            }
            
            User user = (User)request.getSession().getAttribute( AuthFilter.USER_SESSION_KEY );
            user.setMoney(moneyBigDec);
            UserDao userDao = new UserDao();
            userDao.updateMoney( user );
            
            
            return new BooksList().perform(request, response);
            
        }catch(SQLException e){
            System.out.println("Db error ");
            e.printStackTrace();
            return Constants.FATAL_ERROR_PAGE_PATH;
        }
    }

}

